<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>评论管理</span>
        <el-button type="primary" @click="openCreateReviewDrawer">新增评论</el-button>
      </div>
    </template>
    <el-table :data="tableData" stripe :height="600" style="width: 100%">
      <el-table-column prop="userId" label="用户ID"/>
      <el-table-column prop="hotelName" label="酒店名称"/>
      <el-table-column prop="content" label="评论内容"/>
      <el-table-column label="评分">
        <template #default="{ row }">
          <el-rate v-model="row.rating" disabled show-score />
        </template>
      </el-table-column>
      <el-table-column label="评论时间">
        <template #default="{ row }">
          {{ formatDate(row.reviewTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180px">
        <template #default="{ row }">
          <el-button type="primary" :icon="Edit" circle @click="openUpdateReviewDrawer(row)"/>
          <el-button type="danger" :icon="Delete" circle @click="handleDelete(row)"/>
          <el-button type="success" :icon="ChatDotRound" circle @click="viewReviewDetail(row)"/>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-box">
      <el-pagination background layout="total, sizes, prev, pager, next"
                     v-model:current-page="pageIndex"
                     v-model:page-size="pageSize"
                     :page-sizes="[10, 20, 50, 100]"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange"
                     :total="total"/>
    </div>
    <create-review ref="createReviewRef" @refresh="initData"/>
    <update-review ref="updateReviewRef" @refresh="initData"/>

    <!-- 评价详情对话框 -->
    <el-dialog v-model="reviewDetailVisible" title="评论详情" width="50%">
      <div v-if="currentReview" class="review-detail">
        <div class="review-header">
          <div class="review-user">用户ID: {{ currentReview.userId }}</div>
          <div class="review-time">{{ formatDate(currentReview.reviewTime) }}</div>
        </div>
        <div class="review-hotel">
          <span>酒店名称: </span>
          <span>{{ currentReview.hotelName }}</span>
        </div>
        <div class="review-rating">
          <span>评分: </span>
          <el-rate v-model="currentReview.rating" disabled show-score />
        </div>
        <el-divider />
        <div class="review-content">
          <h3>评论内容:</h3>
          <p>{{ currentReview.content }}</p>
        </div>
        
        <el-divider />
        <div class="reply-section">
          <h3>评论回复:</h3>
          <div v-if="loading" class="loading">
            <el-skeleton :rows="3" animated />
          </div>
          <div v-else-if="replies.length === 0" class="no-replies">
            暂无回复
          </div>
          <div v-else class="reply-list">
            <div v-for="(reply, index) in replies" :key="index" class="reply-item">
              <div class="reply-header">
                <span class="reply-user">{{ reply.userId }}</span>
                <span class="reply-time">{{ formatDate(reply.replyTime) }}</span>
              </div>
              <div class="reply-content">{{ reply.content }}</div>
            </div>
          </div>
          
          <div class="add-reply">
            <h3>添加回复</h3>
            <el-input
              v-model="replyContent"
              type="textarea"
              :rows="3"
              placeholder="请输入回复内容"
            />
            <div class="reply-actions">
              <el-button type="primary" @click="submitReply" :loading="submitting">提交回复</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { getReviewList, deleteReview, getReviewReplies, addReviewReply } from '@/api/review'
import { Edit, Delete, ChatDotRound } from '@element-plus/icons-vue'
import CreateReview from './components/CreateReview.vue'
import UpdateReview from './components/UpdateReview.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const tableData = ref([])
const total = ref(0)
const pageIndex = ref(1)
const pageSize = ref(20)
const createReviewRef = ref()
const updateReviewRef = ref()

// 评论详情相关
const reviewDetailVisible = ref(false)
const currentReview = ref(null)
const replies = ref([])
const loading = ref(false)
const replyContent = ref('')
const submitting = ref(false)

// 格式化日期
const formatDate = (dateStr: string | null) => {
  if (!dateStr) return '-';
  const date = new Date(dateStr);
  return date.toLocaleString();
};

const initData = () => {
  console.log('开始获取评论列表数据...');
  
  getReviewList()
    .then(res => {
      console.log('获取评论列表响应:', res);
      
      // 正确处理后端响应
      const result = res.data as any;
      console.log('后端返回的原始数据结构:', result);
      
      // 检查返回的数据结构
      if (Array.isArray(result)) {
        // 直接返回数组格式的数据
        tableData.value = result;
        total.value = result.length;
        console.log('处理后的评论数据:', tableData.value);
        
        if (tableData.value.length > 0) {
          console.log('第一条评论数据的字段名:', Object.keys(tableData.value[0]));
        } else {
          console.log('评论列表为空');
        }
      } else if (result && result.code === 200) {
        // 标准响应格式：{code: 200, data: [...], msg: '...'}
        tableData.value = Array.isArray(result.data) ? result.data : [];
        total.value = tableData.value.length;
        
        console.log('处理后的评论数据:', tableData.value);
        
        if (tableData.value.length > 0) {
          console.log('第一条评论数据的字段名:', Object.keys(tableData.value[0]));
        } else {
          console.log('评论列表为空');
        }
      } else if (result && result.code === 0) {
        // 另一种可能的成功响应格式：{code: 0, data: [...], msg: '请求成功'}
        tableData.value = Array.isArray(result.data) ? result.data : [];
        total.value = tableData.value.length;
        
        console.log('处理后的评论数据:', tableData.value);
        
        if (tableData.value.length > 0) {
          console.log('第一条评论数据的字段名:', Object.keys(tableData.value[0]));
        } else {
          console.log('评论列表为空');
        }
      } else {
        console.error('获取评论列表失败:', result);
        ElMessage.error(result?.msg || '获取评论列表失败');
      }
    })
    .catch(error => {
      console.error('获取评论列表错误:', error);
      ElMessage.error('网络错误，获取评论列表失败');
    });
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  initData()
}
const handleCurrentChange = (index: number) => {
  pageIndex.value = index
  initData()
}
const openCreateReviewDrawer = () => {
  createReviewRef.value.open()
}
const openUpdateReviewDrawer = (row: any) => {
  updateReviewRef.value.open(row)
}
const handleDelete = (row: any) => {
  // 检查可能的ID字段
  const reviewId = row.id || row.reviewId || row.review_id || row.commentId;
  
  if (!reviewId) {
    console.error('无法确定评论ID，评论对象：', row);
    ElMessage.error('无法获取评论ID，无法删除');
    return;
  }
  
  ElMessageBox.confirm('确定要删除该评论吗？', '提示', { type: 'warning' })
    .then(() => {
      console.log('准备删除评论，评论ID:', reviewId);
      
      deleteReview(reviewId)
        .then(res => {
          console.log('删除评论响应:', res);
          
          const result = res.data as any;
          
          // 检查返回的数据结构
          if (result === true || result === 'success' || result === 1) {
            // 直接返回成功标志
            ElMessage.success('删除成功');
            initData();
          } else if (result && (result.code === 200 || result.code === 0)) {
            // 标准响应格式
            ElMessage.success('删除成功');
            initData();
          } else {
            console.error('删除评论失败:', result);
            ElMessage.error(result?.msg || '删除失败');
          }
        })
        .catch(error => {
          console.error('删除评论错误:', error);
          ElMessage.error('网络错误，删除评论失败');
        });
    })
    .catch(() => {
      // 用户取消操作
      console.log('用户取消删除操作');
    });
}

// 查看评论详情
const viewReviewDetail = (row) => {
  console.log('管理员评论详情对象：', row)
  console.log('评论对象字段：', Object.keys(row))
  
  // 确保row对象可以被正确复制
  try {
    // 创建一个新对象，确保reviewId字段存在
    const reviewObj = {
      ...row,
      // 如果原对象没有reviewId字段但有id字段，添加reviewId
      reviewId: row.reviewId || row.id || null
    }
    
    currentReview.value = reviewObj
    console.log('处理后的评论对象:', currentReview.value)
  } catch (error) {
    console.error('处理评论对象时出错:', error)
    currentReview.value = row
  }
  
  reviewDetailVisible.value = true
  replyContent.value = ''
  
  // 检查可能的ID字段
  const possibleIdField = row.id || row.reviewId || row.review_id || row.commentId || null
  console.log('找到的可能ID字段：', possibleIdField)
  
  if (!possibleIdField) {
    console.error('无法确定评论ID，评论对象：', row)
    ElMessage.warning('无法获取评论ID，无法加载回复')
    replies.value = []
    return
  }
  
  loadReplies(possibleIdField)
}

// 加载评论回复
const loadReplies = (reviewId) => {
  if (!reviewId) {
    ElMessage.warning('评论ID不存在，无法加载回复')
    replies.value = []
    return
  }
  
  // 确保reviewId为数字类型
  const numericReviewId = Number(reviewId)
  console.log('加载评论回复，处理后的评论ID:', numericReviewId, '类型:', typeof numericReviewId)
  
  if (isNaN(numericReviewId)) {
    console.error('评论ID无法转换为数字:', reviewId)
    ElMessage.error('评论ID格式错误')
    replies.value = []
    return
  }
  
  loading.value = true
  getReviewReplies(numericReviewId)
    .then(res => {
      console.log('获取评论回复响应结果:', res)
      
      // 处理直接返回数组的情况
      if (Array.isArray(res)) {
        console.log('响应直接是数组:', res)
        replies.value = res
        return
      }
      
      // 处理返回对象中data为数组的情况
      const result = res.data as any
      console.log('响应数据:', result)
      
      // 直接返回数组的情况（result本身就是数组）
      if (Array.isArray(result)) {
        console.log('响应数据是数组:', result)
        replies.value = result
        return
      }
      
      // 标准响应结构 {code:200, data:[...]}
      if (result && result.code === 200) {
        if (Array.isArray(result.data)) {
          replies.value = result.data
          console.log('解析后的回复列表:', replies.value)
        } else if (result.data && Array.isArray(result.data.records)) {
          replies.value = result.data.records
          console.log('从records字段中获取回复列表:', replies.value)
        } else {
          console.warn('回复数据格式不是数组:', result.data)
          replies.value = []
        }
      } else {
        console.error('获取评论回复失败，返回结果:', result)
        ElMessage.error(result?.msg || '获取评论回复失败')
        replies.value = []
      }
    })
    .catch(error => {
      console.error('获取评论回复失败:', error)
      ElMessage.error('网络错误，获取评论回复失败')
      replies.value = []
    })
    .finally(() => {
      loading.value = false
    })
}

// 提交回复
const submitReply = () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('回复内容不能为空')
    return
  }
  
  if (!currentReview.value) {
    ElMessage.error('评论数据不存在，无法提交回复')
    return
  }
  
  console.log('当前评论对象:', currentReview.value)
  
  // 检查可能的ID字段
  const reviewId = currentReview.value.id || currentReview.value.reviewId || currentReview.value.review_id || currentReview.value.commentId
  
  if (!reviewId) {
    console.error('无法确定评论ID，评论对象：', currentReview.value)
    ElMessage.error('无法获取评论ID，无法提交回复')
    return
  }
  
  // 确保reviewId为数字类型
  const numericReviewId = Number(reviewId)
  console.log('提交回复的评论ID:', numericReviewId, '类型:', typeof numericReviewId)
  
  if (isNaN(numericReviewId)) {
    console.error('评论ID无法转换为数字:', reviewId)
    ElMessage.error('评论ID格式错误')
    return
  }
  
  submitting.value = true
  
  const replyData = {
    reviewId: numericReviewId,
    userId: 'admin', // 管理员回复，固定使用admin
    content: replyContent.value
  }
  
  console.log('准备提交回复数据:', JSON.stringify(replyData))
  
  addReviewReply(replyData)
    .then(res => {
      console.log('添加回复响应结果:', res)
      
      // 处理直接返回布尔值的情况
      if (typeof res === 'boolean') {
        if (res) {
          ElMessage.success('回复提交成功')
          replyContent.value = ''
          loadReplies(numericReviewId)
        } else {
          ElMessage.error('回复提交失败')
        }
        return
      }
      
      const result = res.data as any
      if (result === true || result === 'success' || result === 1 || 
          (result && (result.code === 200 || result.code === 0))) {
        ElMessage.success('回复提交成功')
        replyContent.value = ''
        loadReplies(numericReviewId)
      } else {
        ElMessage.error(result?.msg || '回复提交失败')
      }
    })
    .catch(error => {
      console.error('提交回复失败:', error)
      ElMessage.error('网络错误，回复提交失败')
    })
    .finally(() => {
      submitting.value = false
    })
}

onMounted(() => {
  initData()
})
</script>
<style scoped>
.header { display: flex; justify-content: space-between; align-items: center; }
.pagination-box { padding-top: 16px; display: flex; justify-content: right; }

/* 评论详情样式 */
.review-detail {
  padding: 10px;
}
.review-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}
.review-user {
  font-weight: bold;
}
.review-time {
  color: #999;
}
.review-hotel, .review-rating {
  margin-bottom: 15px;
}
.review-content {
  margin-bottom: 20px;
}
.review-content p {
  white-space: pre-wrap;
  line-height: 1.6;
}
.reply-section {
  margin-top: 20px;
}
.no-replies {
  text-align: center;
  padding: 20px;
  color: #909399;
  background: #f8f8f9;
  border-radius: 4px;
  margin-bottom: 20px;
}
.reply-list {
  margin-bottom: 20px;
}
.reply-item {
  padding: 10px;
  border-bottom: 1px solid #eee;
  margin-bottom: 10px;
}
.reply-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 5px;
}
.reply-user {
  font-weight: bold;
}
.reply-time {
  color: #909399;
  font-size: 12px;
}
.reply-content {
  line-height: 1.6;
}
.add-reply {
  margin-top: 20px;
}
.reply-actions {
  margin-top: 10px;
  text-align: right;
}
</style>
